import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    redirect: '/welcome',
    component: () => import('../views/home/home.vue'),
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: () => import('../components/welcome.vue')
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('../views/user/index.vue')
      },
      {
        path: '/roles',
        name: 'Roles',
        component: () => import('../views/power/roles.vue')
      },
      {
        path: '/rights',
        name: 'Rights',
        component: () => import('../views/power/rights.vue')
      },
      {
        path: '/goods',
        name: 'Goods',
        component: () => import('../views/shop/goods.vue')
      },{
        path:'/add',
        name:'Add',
        component:()=> import('../views/shop/add.vue')
      },{
        path:'/params',
        name:'Params',
        component:()=> import('../views/shop/params.vue')
      },{
        path:'/categories',
        name:'Categories',
        component:()=> import('../views/shop/categories.vue')
      },{
        path:'/orders',
        name:'Orders',
        component:()=> import('../views/orders/index.vue')
      }
    ]
  },

]

const router = new VueRouter({
  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
  let token = window.sessionStorage.getItem('token')
  if (to.path == '/login') token ? next('home') : next()//如果要前往login页面判断token是否存在，存在就不能去login跳到home页，没有token就可以执行下一步
  if (!token) return next('/login')
  next()
})
export default router
